package com.xoa.global.timedTask;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.workflow.FlowTimerMapper;
import com.xoa.model.department.Department;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowTimerWithBLOBs;
import com.xoa.service.users.UsersService;
import com.xoa.util.common.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by 刘建 on 2020/7/12 15:49
 * 定时任务-自动发起流程
 * com.xoa.service.TimerSchedule.TimerWorkflowNew.flowNew()
 */
@Component
public class NewFlowWork {

    @Resource
    FlowTimerMapper flowTimerMapper;

    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    UsersService usersService;


    public void flowNew() {
        System.out.println("44444444444444");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date date=new Date();
        String format = sdf.format(date);// 时分秒
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH)+1;//获取月份  默认0-11
        int day=cal.get(Calendar.DATE);//获取日
        int hour=cal.get(Calendar.HOUR);//小时
        int minute=cal.get(Calendar.MINUTE);//分
        int second=cal.get(Calendar.SECOND);//秒
        int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK)-1;//一周的第几天 默认星期日为1 星期一为2 所以减一
        if (WeekOfYear == 0) {//默认
            WeekOfYear = 7;
        }
        // 系统刷新时间
        int Refresh = 1;
        List<FlowTimerWithBLOBs> flowTimerWithBLOBs = flowTimerMapper.selectAll(format,Refresh,date);
        System.out.println("66666666666666666666666666666666。。。。");
        List<FlowTimerWithBLOBs> result=employ(flowTimerWithBLOBs);
        if(result!=null&&result.size()>0){
            System.out.println("77777777777777777777777777777777777。。。。");
            execute(result);
        }
    }

    private void execute(List<FlowTimerWithBLOBs> result) {
        System.out.println("88888888888888888888888888888888。。。。");
        for (FlowTimerWithBLOBs res1:result){
            StringBuffer userStr=new StringBuffer();
            String[] userIdList=res1.getUserStr().split(",");

            List<String> userArray=new ArrayList();

            for(String userId:userIdList){
                userArray.add(userId);
            }
            //部门人员
            List<Users> deptList=new ArrayList();
            if(!StringUtils.checkNull(res1.getDeptStr())){
                if("ALL_DEPT".trim().equals(res1.getDeptStr())){
                    List<Department>  deptListArr=departmentMapper.getAllDepartment();
                    StringBuffer stringBuffer=new StringBuffer();
                    for(Department department:deptListArr){
                        stringBuffer.append(department.getDeptId());
                        stringBuffer.append(",");
                    }
                    // flag 1 主部门  2 角色  3 辅助部门 4 辅助角色 5 部门和辅助部门  6 角色和辅助角色
                    deptList=usersService.getUserByDeptIds(stringBuffer.toString(),1);
                }else {
                    deptList=usersService.getUserByDeptIds(res1.getDeptStr(),5);
                }

            }
            List<String> deptArray=new ArrayList();
            for(Users users:deptList){
                deptArray.add(users.getUserId());
            }

            //角色人员
            List<Users> privList=new ArrayList();
            if(!StringUtils.checkNull(res1.getPrivStr())){
                privList=usersService.getUserByDeptIds(res1.getPrivStr(),6);
            }
            List<String> privArray=new ArrayList();
            for(Users users:privList){
                privArray.add(users.getUserId());
            }

            //删除重复的数据
            for(String userId:userArray){
                int f1=0;
                for(String deptUser:deptArray){
                    if(userId.equals(deptUser)){
                        f1=1;
                        break;
                    }
                }
                if(f1==0){
                    deptArray.add(userId);
                }
            }
            for(String temp1:deptArray){
                int f2=0;
                for(String privUser:privArray){
                    if(temp1.equals(privUser)){
                        f2=1;
                        break;
                    }
                }
                if(f2==0){
                    privArray.add(temp1);
                }
            }
            for(String tempUser:privArray){
                userStr.append(tempUser+",");
            }
            //开始新建流程，发送事务提醒
            newFlowAndRemind(res1,userStr.toString());

        }
    }

    private void newFlowAndRemind(FlowTimerWithBLOBs res1, String users1) {
        String[] users = users1.split(",");
        for (String user:users){
            //workController.newFlow(res1.getFlowId(),1,"1","0");
            res1.getFlowId();
        }
    }

    public List<FlowTimerWithBLOBs> employ(List<FlowTimerWithBLOBs> flowTimerWithBLOBs){
        //记录可执行的定时任务
        List<FlowTimerWithBLOBs> flowTimers=new ArrayList<FlowTimerWithBLOBs>();
        if(flowTimerWithBLOBs!=null&&flowTimerWithBLOBs.size()>0){
            Date date=new Date();
            for(FlowTimerWithBLOBs flowTimerWith:flowTimerWithBLOBs){
                //查看是否执行
                // 传入时间  防止程序造成时差
                boolean flag=isStart(flowTimerWith,date);
                if(flag){
                    flowTimers.add(flowTimerWith);
                }
            }
        }
        return flowTimers;
    }

    //判断是否纳入执行之中
    public boolean isStart(FlowTimerWithBLOBs flowTimerWithBLOBs,Date date){
        //获取当前系统时间
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH)+1;//获取月份  默认0-11
        int day=cal.get(Calendar.DATE);//获取日
        int hour=cal.get(Calendar.HOUR);//小时
        int minute=cal.get(Calendar.MINUTE);//分
        int second=cal.get(Calendar.SECOND);//秒
        int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK)-1;//一周的第几天 默认星期日为1 星期一为2 所以减一
        if (WeekOfYear == 0) {//默认
            WeekOfYear = 7;
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(date.getTime()>flowTimerWithBLOBs.getRemindTime().getTime()){
            //如果当前时间大于开始执行时间
            //获取当前定时器最后一次启动的记录  如果为null则代表没有执行记录，立刻执行
            //TimedTaskRecord timedTaskRecord =timedTaskRecordMapper.selectTimedTaskTypeseLastOne(timedTaskManagement.getTtmId());
            if(flowTimerWithBLOBs.getLastTime()==null){
                return true;
            }
            //获取时间间隔
            Long outTime=1L;
            //获取间隔类型
            Integer typeMet=Integer.parseInt(flowTimerWithBLOBs.getType());
            if(typeMet==1){
                //一次任务
                return true;
            }else if (typeMet==2 ){
                //定点任务  单位为天
                return true;
            }else if (typeMet==3 && WeekOfYear==Integer.parseInt(flowTimerWithBLOBs.getRemindDate())){//当前周几 与数据库比较
                //定点任务  单位为周
                return true;
            }else if (typeMet==4 && day==Integer.parseInt(flowTimerWithBLOBs.getRemindDate())){
                //定点任务  单位为月
                return true;
            }else if (typeMet==5){
                //定点任务  单位为年
                return true;
            }
        }
        return false;
    }

}
